module.exports = options => {
    const jwt = require('jsonwebtoken')
    const AdminUser = require('../models/AdminUser')
    const assert = require('http-assert')
    
    return async (req, res, next) => {
        // 获取请求头 后端全部用小写 前端用大写
        const token = String(req.headers.authorization || '').split(' ').pop() // pop最后一个元素
        // console.log(token);
        assert(token, 401, '请先登入')

        // 解密获取id
        const { id } = jwt.verify(token, req.app.get('secret'))
        assert(token, 401, '请先登入')

        // 找到id 并赋值
        req.user = await AdminUser.findById(id)
        assert(req.user, 401, '请先登入')

        // console.log(req.user);
        await next()
    }
}